import { memo, useEffect, useMemo, useRef, useState } from "react";
import { CardRecordType } from "../../types/cardRecord";
import CardRecordStyle from "./style";
import { useFetch_getCrouseInfo } from "../../service/course";
import { CourseType } from "../../types/course";
import { CardType, CardTypeType } from "../../types/card";
import { useGetOrganizationInfo } from "../../service/organization";
import { CreditCardOutlined } from "@ant-design/icons";
import { Tag } from "antd-mobile";
import classNames from "classnames";

const Card = memo((props: { data: CardRecordType; isObsolete: boolean }) => {
  const { data, isObsolete } = props;
  const obsolete = useRef(isObsolete);
  const cardData = useMemo(
    () => JSON.parse(data?.card as string) as CardType,
    [data?.card]
  );
  const stashInfo: { title: string; value: string } = useMemo(() => {
    switch (cardData?.type) {
      case CardTypeType.TIME: {
        return {
          title: "次数卡",
          value: `剩余次数 ${data?.residueTime}`,
        };
      }
      case CardTypeType.DURATION: {
        return {
          title: "时长卡",
          value: `有效期至 ${data?.endTime}`,
        };
      }
    }
  }, [cardData, data]);
  const [courseData, setCourseData] = useState<CourseType>();
  const { data: orgData } = useGetOrganizationInfo(data?.orgId);
  const [getCourseData] = useFetch_getCrouseInfo() as [
    (id: string) => Promise<CourseType>
  ];
  useEffect(() => {
    void getCourseData(data?.courseId).then((res) => {
      setCourseData(res);
    });
  }, [data?.courseId]);

  return (
    <CardRecordStyle>
      <div
        className={classNames("cardWrapper", {
          obsoleteCard: obsolete.current,
        })}
      >
        <div className="info">
          <div className="cardName">
            <CreditCardOutlined />
            &nbsp;
            {cardData?.name}
          </div>
          <div className="orgName">{"门店：" + orgData?.name}</div>
          <div className="courseName">{"课程：" + courseData?.name}</div>
        </div>
        <div className="detail">
          <Tag
            className="cardType"
            color={
              cardData.type === CardTypeType.DURATION
                ? "var(--themeColor1)"
                : "var(--themeColor2)"
            }
          >
            {stashInfo?.title}
          </Tag>
          <div className="stash">{stashInfo?.value}</div>
        </div>
      </div>
    </CardRecordStyle>
  );
});

export default Card;
